package org.db2.project.airline.dao.impl;

import org.db2.project.airline.dao.DAOException;
import org.db2.project.airline.dao.GenericDAO;
import org.hibernate.HibernateException;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

/**
 *
 */
@SuppressWarnings("unchecked")
public class HibernateGenericDAO<T> extends HibernateBaseDAO implements GenericDAO<T> {

    /**
     * <p>Represents the entity class.</p>
     */
    Class<T> entityClass;

    public HibernateGenericDAO() {

        entityClass = (Class<T>)
                ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    @Override
    public void save(T entity) throws DAOException {

        try {

            getSession().save(entity);
        } catch (HibernateException exc) {

            throw new DAOException("Error occurred when saving entity in persistence.", exc);
        }
    }

    @Override
    public void update(T entity) throws DAOException {

        try {

            getSession().update(entity);
        } catch (HibernateException exc) {

            throw new DAOException("Error occurred when updating entity in persistence.", exc);
        }
    }

    @Override
    public void delete(T entity) throws DAOException {

        try {

            getSession().delete(entity);
        } catch (HibernateException exc) {

            throw new DAOException("Error occurred when deleting entity from persistence.", exc);
        }
    }

    @Override
    public T find(Serializable id) throws DAOException {

        try {

            return (T) getSession().get(entityClass, id);
        } catch (HibernateException exc) {

            throw new DAOException("Error occurred when retrieving entity from persistence.", exc);
        }
    }

    @Override
    public List<T> findAll() throws DAOException {

        try {

            return getSession().createQuery(String.format("from %s", entityClass.getSimpleName())).list();
        } catch (HibernateException exc) {

            throw new DAOException("Error occurred when retrieving entities from persistence.", exc);
        }
    }
}
